const jwt = require('jsonwebtoken');
const User = require('../models/userModel');
const Response = require('../utils/response');

const authenticate = async (ctx, next) => {
    try {
        const token = ctx.headers.authorization;
        if (!token) {
            ctx.status = 401;
            ctx.body = Response.error('未提供认证令牌', 401);
            return;
        }

        try {
            // 解析 token
            const decoded = jwt.verify(token, process.env.JWT_SECRET);
            // 查找用户
            const user = await User.findOne({ id: decoded.id });

            if (!user) {
                ctx.status = 401;
                ctx.body = Response.error('用户不存在', 401);
                return;
            }

            // 将完整的用户信息存储在 ctx.state 中
            ctx.state.user = {
                id: user.id,
                username: user.username,
                role: user.role,
                nickName: user.nickName,
                state: user.state
            };
            
            await next();
        } catch (error) {
            ctx.status = 401;
            ctx.body = Response.error('无效的认证令牌', 401);
        }
    } catch (error) {
        ctx.status = 500;
        ctx.body = Response.error('认证过程发生错误');
    }
};

module.exports = {
    authenticate
}; 